/**
 * @开发版权 
 * @项目名称 轻量数据中台(LDMP)
 * @版本信息 v1.0
 * @开发人员 zhous
 * @开发日期 2025-01-17
 * @修订日期
 * @描述  DictController
 */
package com.ng.sys.controller;

import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.ng.common.annotation.TokenRequired;
import com.ng.common.annotation.Tx;
import com.ng.common.controller.Controller;
import com.ng.common.model.response.R;
import com.ng.common.util.UuidUtil;
import com.ng.sys.model.domain.Dict;
import com.ng.sys.model.domain.DictItem;
import com.ng.sys.model.dto.DictDTO;
import com.ng.sys.model.dto.DictItemDTO;
import com.ng.sys.service.IDict;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;

@Tag(name = "字典管理")
@RequiredArgsConstructor
@RestController
@RequestMapping("/sys/dict")
public class DictController extends Controller{

	@Autowired
	private IDict dictImpl;
	
	@Operation(summary = "字典树")
	@Parameters({ @Parameter(name = "keywords", description = "关键字", required = false)})
	@TokenRequired
	@GetMapping(value = { "/tree" }, produces = "application/json; charset=utf-8")
	public R<List<Dict>> tree(HttpServletRequest request,
			@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords) {
		String _sql = "select * from " + Dict.TABLE_NAME + " a where 1=1 ";

		if (!StrKit.isBlank(keywords)) {
			_sql += " and a.name like '%" + keywords + "%'   ";
		}
		_sql += " order by a.sort asc";
		return R.ok(Dict.dao.find(_sql));
	}
	
	@Operation(summary = "字典列表")
	@Parameters({ @Parameter(name = "keywords", description = "关键字", required = false),
		@Parameter(name = "dictId", description = "字典id", required = false),
		@Parameter(name = "state", description = "字典项状态(0-禁用 1-启用)", required = false),
		@Parameter(name = "cur", description = "当前页码", required = true),
		@Parameter(name = "limit", description = "每页数据量", required = true)})
	@TokenRequired
	@GetMapping(value = { "/pages" }, produces = "application/json; charset=utf-8")
	public R<Page<Dict>> pages(HttpServletRequest request,
			@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
			@RequestParam(name = "dictId", required = false, defaultValue = "") String dictId,
			@RequestParam(name = "dict", required = false, defaultValue = "") String dict,
			@RequestParam(name = "state", required = false, defaultValue = "") String state,
			@RequestParam(name = "cur", required = false, defaultValue = "1") int cur,
			@RequestParam(name = "limit", required = false, defaultValue = "10") int limit) throws Exception {
		String sqlExceptSelect = " from " + Dict.TABLE_NAME + "  a WHERE 1=1 ";
		if (!StrKit.isBlank(keywords)) {
			sqlExceptSelect += " and ( a.name like '%" + keywords + "%' or a. code  like '%" + keywords + "%')  ";
		}
		if (!StrKit.isBlank(state)) {
			sqlExceptSelect += " and a.status = '" + state + "' ";
		}
		sqlExceptSelect += "  ORDER BY a.sort asc ";
		return R.ok(Dict.dao.paginate(cur, limit, "select a.* ", sqlExceptSelect));
	}
	
	@Operation(summary = "字典")
	@Parameters({ @Parameter(name = "keywords", description = "关键字", required = false), @Parameter(name = "code", description = "标识", required = false)})
	@TokenRequired
	@GetMapping(value = { "/list" }, produces = "application/json; charset=utf-8")
	public R<List<DictDTO>> list(HttpServletRequest request,@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,@RequestParam(name = "code", required = false, defaultValue = "") String code) {
		String _sql = "select * from " + Dict.TABLE_NAME + " a where 1=1 ";

		if (!StrKit.isBlank(keywords)) {
			_sql += " and a.name like '%" + keywords + "%'   ";
		}
		if (!StrKit.isBlank(code)) {
			_sql += " and a.code = '" + code + "'   ";
		}
		_sql += " order by a.sort asc";
		List<Dict> list=Dict.dao.find(_sql);
		List<DictDTO> dictDTOList=new LinkedList<DictDTO>();
		DictDTO dictDTO;
		DictItemDTO dictItemDTO;
		List<DictItemDTO> dictDataList;
		List<DictItem> dictItems;
		for(Dict dict:list) {
			dictDTO=new DictDTO();
			dictDTO.setName(dict.getName());
			dictDTO.setCode(dict.getCode());
			dictItems=DictItem.dao.find("select * from "+DictItem.TABLE_NAME+" where dict_id=? order by sort asc " ,dict.getId());
			if(dictItems!=null) {
				dictDataList=new LinkedList<DictItemDTO>();
				for(DictItem dictItem:dictItems) {
					dictItemDTO=new DictItemDTO();
					dictItemDTO.setLabel(dictItem.getName());
					dictItemDTO.setValue(dictItem.getValue());
					dictDataList.add(dictItemDTO);
				}
				dictDTO.setDictDataList(dictDataList);
			}
			dictDTOList.add(dictDTO);
		}
		return R.ok(dictDTOList);
	}
	
	
	@Operation(summary = "保存字典")
	@Parameters({ @Parameter(name = "dict", description = "字典", required = true)})
	@Tx
	@TokenRequired
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public R<Dict> save(HttpServletRequest request,@RequestBody Dict dict) {
		if (StrKit.isBlank(dict.getId())) {
			Dict checkDict=Dict.dao.findFirst("select * from "+Dict.TABLE_NAME+" where code=? ",dict.getCode());
			if(checkDict!=null) {
				return R.failed("字典code已存在.");
			}
			
			dict.setId(UuidUtil.getUUID());
			if(StrKit.isBlank(dict.getParentId())) {
				dict.setParentId("-1");
			}
			dict.setCreateUserId(getUserId(request));
			if (dict.save())
				return R.ok();
		}
		
		Dict checkDict=Dict.dao.findFirst("select * from "+Dict.TABLE_NAME+" where id!=? and code=? ",dict.getId(),dict.getCode());
		if(checkDict!=null) {
			return R.failed("字典code已存在.");
		}
		
		dict.setUpdateUserId(getUserId(request));
		if (dict.update())
			return R.ok();
		return R.failed();
	}

	@Operation(summary = "删除字典")
	@Parameters({ @Parameter(name = "ids", description = "字典id集合", required = true)})
	@DeleteMapping("/{ids}")
	@TokenRequired
	@Tx
	public R<String> delete(@PathVariable("ids") String ids) {
		String[] arr=ids.split(",");
		if(ids==null || ids.length()<=0) {
			return R.failed("请选择需要删除的字典.");
		}
		for(String id:arr) {
			dictImpl.delete(id);
		}
		return R.ok();
	}

	@Operation(summary = "字典项列表")
	@Parameters({ @Parameter(name = "keywords", description = "关键字", required = false),
		@Parameter(name = "dictId", description = "字典id", required = false),
		@Parameter(name = "state", description = "字典项状态(0-禁用 1-启用)", required = false),
		@Parameter(name = "cur", description = "当前页码", required = true),
		@Parameter(name = "limit", description = "每页数据量", required = true)})
	@TokenRequired
	@GetMapping(value = { "/item/pages" }, produces = "application/json; charset=utf-8")
	public R<Page<DictItem>> itemPages(HttpServletRequest request,
			@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
			@RequestParam(name = "dictId", required = false, defaultValue = "") String dictId,
			@RequestParam(name = "dict", required = false, defaultValue = "") String dict,
			@RequestParam(name = "state", required = false, defaultValue = "") String state,
			@RequestParam(name = "cur", required = false, defaultValue = "1") int cur,
			@RequestParam(name = "limit", required = false, defaultValue = "10") int limit) throws Exception {
		String sqlExceptSelect = " from " + DictItem.TABLE_NAME + "  a WHERE 1=1 ";
		
		if (!StrKit.isBlank(keywords)) {
			sqlExceptSelect += " and ( a.name like '%" + keywords + "%' or a. value  like '%" + keywords + "%')  ";
		}
		
		if (!StrKit.isBlank(dictId)) {
			sqlExceptSelect += " and a.dict_id = '" + dictId + "' ";
		}
		
		if (!StrKit.isBlank(state)) {
			sqlExceptSelect += " and a.status = '" + state + "' ";
		}
		sqlExceptSelect += "  ORDER BY a.sort asc ";
		return R.ok(DictItem.dao.paginate(cur, limit, "select a.* ", sqlExceptSelect));
	}
	
	@Operation(summary = "保存字典项")
	@Parameters({ @Parameter(name = "dictItem", description = "字典项", required = true)})
	@Tx
	@TokenRequired
	@RequestMapping(value = "/item/save", method = RequestMethod.POST)
	public R<DictItem> saveItem(HttpServletRequest request,@RequestBody DictItem dictItem) {
		if (StrKit.isBlank(dictItem.getId())) {
			
			DictItem checkDictItem=DictItem.dao.findFirst("select * from "+DictItem.TABLE_NAME+" where dict_id=? and value=? ",dictItem.getId(),dictItem.getValue());
			if(checkDictItem!=null) {
				return R.failed("字典值已存在.");
			}
			
			dictItem.setCreateUserId(getUserId(request));
			dictItem.setId(UuidUtil.getUUID());
			if (dictItem.save())
				return R.ok();
		}
		
		DictItem checkDictItem=DictItem.dao.findFirst("select * from "+DictItem.TABLE_NAME+" where id!=? and dict_id=? and value=? ",dictItem.getId(),dictItem.getDictId(),dictItem.getValue());
		if(checkDictItem!=null) {
			return R.failed("字典值已存在.");
		}
		dictItem.setUpdateUserId(getUserId(request));
		if (dictItem.update())
			return R.ok();
		return R.failed();
	}

	@Operation(summary = "删除字典项")
	@Parameters({ @Parameter(name = "ids", description = "字典项id集合", required = true)})
	@DeleteMapping("/item/{ids}")
	@TokenRequired
	public R<String> deleteItem(@PathVariable("ids") String ids) {
		String[] arr=ids.split(",");
		if(ids==null || ids.length()<=0) {
			return R.failed("请选择需要删除的字典项.");
		}
		for(String id:arr) {
			DictItem.dao.deleteById(id);
		}
		return R.ok();
	}

	@Operation(summary = "根据字典id获取下拉列表")
	@Parameters({ @Parameter(name = "keywords", description = "关键字", required = false),
		 @Parameter(name = "id", description = "字典id", required = true)})
	@GetMapping("/options")
	public R<List<Dict>> listOptions(@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,@RequestParam(name = "id", required = true, defaultValue = "") String id) {
		return R.ok(dictImpl.listOptions(keywords,id));
	}

	@Operation(summary = "根据字典code获取下拉列表")
	@Parameters({ @Parameter(name = "typeCode", description = "字典code", required = true)})
    @GetMapping("/{typeCode}/options")
    public R<List<DictItem>> listItemOptions(@PathVariable String typeCode) {
		List<DictItem> list = dictImpl.listItemOptions(typeCode);
        return R.ok(list);
    }
    
}
